import redis from '../config/redis.js'

class CacheService {
  constructor(prefix = 'cache') {
    this.prefix = prefix
  }

  getKey(key) {
    return `${this.prefix}:${key}`
  }

  async get(key) {
    const data = await redis.get(this.getKey(key))
    return data ? JSON.parse(data) : null
  }

  async set(key, value, duration = 300) { // 默认5分钟
    await redis.setex(this.getKey(key), duration, JSON.stringify(value))
  }

  async del(key) {
    await redis.del(this.getKey(key))
  }

  async clear(pattern) {
    const keys = await redis.keys(`${this.prefix}:${pattern || '*'}`)
    if (keys.length) {
      await redis.del(keys)
    }
  }
}

export const productCache = new CacheService('product')
export const bannerCache = new CacheService('banner')
export const userCache = new CacheService('user') 